package com.me.finance.dao;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

public class BasicSessionDAO implements GenericDao,Serializable {
	
	private static final long serialVersionUID = 1L;
	@PersistenceContext
	private EntityManager em;
	
	public EntityManager getEm() {
		return em;
	}

	public <T> T save(T toPersist) {
		 getEm().persist(toPersist);
		 return (T)toPersist;
	}

	public <T> T update(T toPersist) {
		getEm().merge(toPersist);
		return (T)toPersist;
	}

	public <T> void remove(T toPersist) {
		T toRemove = getEm().merge(toPersist);
		getEm().remove(toRemove);
	}

	@SuppressWarnings("unchecked")
	public <T> List<T> getList(Class<T> classToCast, String query,
			Object... values) {
		Query qr = createQuery(query, values);
        return (List<T>) qr.getResultList();
	}

	@SuppressWarnings("unchecked")
	public <T> List<T> getLimitedList(Class<T> classToCast, String query,
			int limit, Object... values) {
		Query qr = createQuery(query, values);
        qr.setMaxResults(limit);
        return (List<T>) qr.getResultList();
	}

	@SuppressWarnings("unchecked")
	public <T> T getSingle(Class<T> classToCast, String query, Object... values) {
		Query qr = createQuery(query, values);
        return (T) qr.getSingleResult();
	}

	public <T> T getSingle(Class<T> classToCast, Serializable primaryKey) {
		return getEm().find(classToCast, primaryKey);
	}
	
	public int executeQuery(String query, Object... values) {
        Query qr = createQuery(query, values);
        return qr.executeUpdate();
    }

    private Query createQuery(String query, Object[] values) {

        Query qr = getEm().createQuery(query);

        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                Object object = values[i];
                qr.setParameter(i + 1, object);
            }
        }

        return qr;
    }

}
